﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ZT.Core.ORM
{
    /// <summary>
    /// 仓储PG
    /// </summary>
    public class RepositoryPG<T> : IRepository<T> where T : Model.ModelBase
    {
        string errmsg = string.Empty;
        internal DbContext dbContext;//当前程序集有效
        internal readonly DbSet<T> dbSet;
        public RepositoryPG(DbContext db)
        {
            dbContext = db;
            dbSet = db.Set<T>();
        }

        public T Insert(T entity)
        {
            dbSet.Add(entity);
            return entity;
        }

        public bool Insert(IEnumerable<T> entitys)
        {
            dbSet.AddRange(entitys);
            return true;
        }
        public IQueryable<T> Queryable(Expression<Func<T, bool>> pridicate = null)
        {
            if (pridicate != null)
            {
                return dbSet.Where(pridicate);
            }
            else
            {
                return dbSet.AsQueryable();
            }
        }

        public bool Any(Guid Id)
        {
            return dbSet.Any(p => p.Id == Id);
        }

        public bool Any(Expression<Func<T, bool>> predicate)
        {
            return dbSet.Any(predicate);
        }

        public T Update(T entity)
        {
            dbSet.Update(entity);
            return entity;
        }

        public T GetModel(Guid Id)
        {
            var entity = dbSet.FirstOrDefault(p => p.Id == Id);
            return entity;
        }

        public T GetModel(Expression<Func<T, bool>> pridicate)
        {
            var entity = dbSet.FirstOrDefault(pridicate);
            return entity;
        }

        public bool Delete(T entity)
        {
            dbSet.Remove(entity);
            return true;
        }

        public bool Delete(Expression<Func<T, bool>> predicate)
        {
            var entities = dbSet.Where(predicate);
            dbSet.RemoveRange(entities);
            return true;
        }
    }
}
